package com.ruoyi.wlw.service.impl;

import com.ruoyi.wlw.common.ElectricityMeterUtil;
import com.ruoyi.wlw.common.InstructConstant;
import com.ruoyi.wlw.common.InstructTypeConstant;
import com.ruoyi.wlw.socket.BootNettyChannelInboundHandlerAdapter;
import com.ruoyi.wlw.domain.IotDevice;
import com.ruoyi.wlw.mapper.IotDeviceMapper;
import com.ruoyi.wlw.service.SendInstructsService;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * 发送指令服务实现类
 */
@Service("sendInstructsService")
@Slf4j
public class SendInstructsServiceImpl implements SendInstructsService {

    @Resource
    private IotDeviceMapper iotDeviceMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object[] sendInstructs(String context, String ip, HttpServletRequest request, String deviceCode, String operationType) {
        log.info("prepare start send instructs0 {} {}", InstructTypeConstant.getByKey(operationType).getValue(), context);
        Long countTimeLong = 0L;
        try {
            a:
            while (true) {
                //防止一台设备同时下发多条指令，如果缓存中有记录则表示上次的操作还未完成
                String type = stringRedisTemplate.opsForValue().get(InstructConstant.handleInstructs + deviceCode);

                if (countTimeLong > 20000) {
                    log.info("send Instructs failed instructs: [{}]", context);
                    //超过20秒没有接到指令的返回，则会自动撤销上次操作
                    stringRedisTemplate.delete(InstructConstant.handleInstructs + deviceCode);
                    break;
                }
                log.info("wait return {}", type);
                Thread.sleep(500);
                countTimeLong = countTimeLong + 500;
                if (StringUtils.isEmpty(type)) {
                    // 20秒
                    stringRedisTemplate.opsForValue().set(InstructConstant.handleInstructs + deviceCode, operationType, 20, TimeUnit.MINUTES);
                    byte[] b = ElectricityMeterUtil.fromHexString(context);
                    ChannelGroup channelGroup = BootNettyChannelInboundHandlerAdapter.getChannels();
                    Iterator channelIterator = channelGroup.iterator();
                    b:
                    while (channelIterator.hasNext()) {
                        Channel channel = (Channel) channelIterator.next();
                        InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
                        //给指定客户端ip发送消息
                        if (ip.equals(insocket.toString())) {
                            log.info("prepare start send instructs  {}", context);
                            channel.writeAndFlush(Unpooled.copiedBuffer(b));
                            channel.flush();
                            log.info(" send instructs end");
                            //发送接收等待结束
                            break a;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return new Object[]{context, ip, request, deviceCode, operationType};
    }

    @Override
    public void handleGateWayStatus(String ip, String str, boolean flag) {
        //心跳监控
    }

    @Override
    public void callbackInstructResultMsg(String ip, String returnStr) {
        log.info(returnStr);

        if (StringUtils.isEmpty(returnStr) || !returnStr.startsWith("FE")) {
            return;
        }
        //获取回调设备编号
        String notFEStr = returnStr.substring(returnStr.indexOf("68") + 2);
        // w-水表   e-电表
        String deviceType = notFEStr.startsWith("10") ? "w" : "e";
        //根据设备号找到数据，并更新数据
        if ("e".equals(deviceType)) {
            String addressNo = notFEStr.substring(0, notFEStr.indexOf("68"));
            //获取设备号
            String deviceNo = ElectricityMeterUtil.addressConvertNo(addressNo, true);
            String operationType = stringRedisTemplate.opsForValue().get(InstructConstant.handleInstructs + deviceNo);
            //删除redis中的数据
            stringRedisTemplate.delete(InstructConstant.handleInstructs + deviceNo);
            //电表操作
            handleOperation(deviceNo, operationType, notFEStr);
        } else {
            //水表操作
            String deviceCode = handleWaterOperation(notFEStr);
            //删除redis中的数据
            stringRedisTemplate.delete(InstructConstant.handleInstructs + deviceCode);
        }
    }

    /**
     * 处理水表返回操作
     *
     * @param notFEStr 返回指令内容
     */
    private String handleWaterOperation(String notFEStr) {
        String deviceNo = "";
//        LambdaQueryWrapper<IotDevice> wrapper = new LambdaQueryWrapper<>();
        IotDevice vo = new IotDevice();
        if (notFEStr.indexOf("A0170000") >= 0) {
            //开阀成功
            //设备号
            deviceNo = notFEStr.substring(2, notFEStr.indexOf("AA05"));
            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo, true);
            vo.setSluiceStatus("1");
        }
        if (notFEStr.indexOf("A0170001") >= 0) {
            //关阀成功
            deviceNo = notFEStr.substring(2, notFEStr.indexOf("AA05"));
            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo, true);
            vo.setSluiceStatus("0");
        }
//        if(notFEStr.indexOf("901F00") >= 0) {
//            deviceNo = notFEStr.substring(2,notFEStr.indexOf("8116901F"));
//            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo,true);
//            //查询水表
//            String data = notFEStr.substring(notFEStr.indexOf("901F00")+6,notFEStr.indexOf("901F")+14);
//            String dataStr  = ElectricityMeterUtil.addressConvertNo(data,true);
//            BigDecimal currWaterCount = new BigDecimal(dataStr).multiply(new BigDecimal("0.01"));
//            log.info("water info {}" , currWaterCount);
//            handleWaterMater(deviceNo,  vo, currWaterCount);
//        }
//        wrapper.eq(IotDevice::getDeviceCode,deviceNo);
        vo.setDeviceCode(deviceNo);
        iotDeviceMapper.update(vo);
        return deviceNo;
    }

    /**
     * 电表处理操作类型，对不同的类型更新对应设备的信息
     *
     * @param deviceNo
     * @param type
     */
    private void handleOperation(String deviceNo, String type, String notFEStr) {
//        LambdaQueryWrapper<IotDevice> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(IotDevice::getDeviceCode,deviceNo);
//        IotDevice vo = new IotDevice();
        IotDevice vo = new IotDevice();
        vo.setDeviceCode(deviceNo);
        //合总电闸，拉闸或合闸后修改设备表状态
        if (InstructTypeConstant.E_MAIN_GATE_NO.getKey().equals(type)) {
            vo.setElectricityStatus("1");
            iotDeviceMapper.update(vo);
        }
        //拉总电闸
        if (InstructTypeConstant.E_MAIN_GATE_OFF.getKey().equals(type)) {
            vo.setElectricityStatus("0");
            iotDeviceMapper.update(vo);
        }
        //合A路电闸
        if (InstructTypeConstant.E_A_GATE_NO.getKey().equals(type)) {
            vo.setElectricityAStatus("1");
            iotDeviceMapper.update(vo);
        }
        //拉A路电闸
        if (InstructTypeConstant.E_A_GATE_OFF.getKey().equals(type)) {
            vo.setElectricityAStatus("0");
            iotDeviceMapper.update(vo);
        }
        //合B路电闸
        if (InstructTypeConstant.E_B_GATE_NO.getKey().equals(type)) {
            vo.setElectricityBStatus("1");
            iotDeviceMapper.update(vo);
        }
        //拉B路电闸
        if (InstructTypeConstant.E_B_GATE_OFF.getKey().equals(type)) {
            vo.setElectricityBStatus("0");
            iotDeviceMapper.update(vo);
        }
//        //获取电表参数信息
//        if (InstructTypeConstant.E_MAIN_PARSM_INFO.getKey().equals(type)) {
//            getElectricityParamInfo(notFEStr, deviceNo);
//        }
//        //获取电表费控数据
//        if (InstructTypeConstant.E_BALANCE_SETUPA.getKey().equals(type)) {
//            getElectricityBalanceInfo(notFEStr, deviceNo);
//        }
    }
}
